import { observable, autorun } from 'mobx'

const cartStore = observable({
  cart: JSON.parse(localStorage.getItem("cart_localStorage_XXX")) || [],
  addCart(item) {
      const index = this.cart.findIndex(cartItem => cartItem.id === item.id)
      if (index === -1) {
        this.cart.push(item)
      } else {
        this.cart[index].count += item.count
      }
  },
  get itemCount() {
    return this.cart.length;
  },
})

/* 观察状态改变的函数 */
autorun(function() {
  localStorage.setItem("cart_localStorage_XXX", JSON.stringify(cartStore.cart.slice()))
});

export default cartStore